// 初始化CodeMirror编辑器
const editor = CodeMirror.fromTextArea(document.getElementById('code-editor'), {
    lineNumbers: true,
    theme: 'dracula',
    mode: 'python',
    indentUnit: 4,
    smartIndent: true,
    matchBrackets: true,
    autoCloseBrackets: true,
});
editor.setValue("# 这是 Python 代码示例\nprint('Hello, World!')");

// 语言切换功能
document.getElementById('language-select').addEventListener('change', (e) => {
    const modeMap = {
        'python': 'python',
        'javascript': 'javascript',
        'json': {name: 'javascript', json: true},
        'java': 'text/x-java'
    };
    editor.setOption('mode', modeMap[e.target.value]);
    var selectedLanguage = e.target.value;
    // 根据选择的语言更新编辑器的模式
    if (selectedLanguage === 'python') {
        editor.setOption('mode', 'python');
        editor.setValue("# 这是 Python 代码示例\nprint('Hello, World!')");
    } else if (selectedLanguage === 'json') {
        editor.setOption('mode', 'json');
        editor.setValue('{\n    "message": "Hello, World!"\n}');
    } else if (selectedLanguage === 'java') {
        editor.setOption('mode', 'text/x-java');
        editor.setValue('// 这是 Java 代码示例\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println("Hello, World!");\n    }\n}');
    }
});

// 获取编辑器内容
function getEditorContent() {
    return {
        content: editor.getValue(),
        language: document.getElementById('language-select').value
    };
}

// 设置编辑器内容和语言
function setEditorContent(content, language) {
    editor.setValue(content);
    document.getElementById('language-select').value = language;
    const modeMap = {
        'python': 'python',
        'javascript': 'javascript',
        'json': {name: 'javascript', json: true},
        'java': 'text/x-java'
    };
    editor.setOption('mode', modeMap[language]);
}

// 获取代码
function getCode() {
    const content = getEditorContent();
    alert(`获取代码成功！\n语言：${content.language}\n内容：\n${content.content}`);
}

// 加载代码
function loadCode() {
    fetch('/api/code')
        .then(response => response.json())
        .then(data => {
            setEditorContent(data.content, data.language);
            alert('代码加载成功！');
        })
        .catch(error => {
            console.error('加载代码失败:', error);
            alert('加载代码失败，请稍后重试');
        });
}

// 暴露函数给全局
window.getEditorContent = getEditorContent;
window.setEditorContent = setEditorContent;
